/*
 * Copyright (c) 2011 Auzingers
 * Created by Oui-IT
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.auzingers.docsorganizer.gui;

import com.auzingers.docsorganizer.R;
import com.auzingers.docsorganizer.entity.GoogleCollection;
import com.auzingers.docsorganizer.entity.GoogleEntry;
import com.auzingers.docsorganizer.googleapi.GoogleAPI;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.io.IOException;
import java.util.Collections;

/**
 * View that shows all collections and allows the user to select one of them.
 */
public class CollectionView extends AbstractGoogleListActivity {

    public static final String PARAM_RESOURCE_TITLE = "resourceTitle";

    public static final String RESULT_SELECTED_RESOURCE_ID = "resourceId";

    private static final int MENU_REFRESH = 1;

    private static final GoogleCollection ROOT_COLLECTION = new GoogleCollection();

    private String paramResourceTitle = "";

    /** Creates a collection view and initializes variables. */
    public CollectionView() {
        ROOT_COLLECTION.setTitle("Root Collection");
        ROOT_COLLECTION.setId(null);
        ROOT_COLLECTION.setResourceId("folder:root");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setListAdapter(new GoogleEntryListAdapter(this, Collections.<GoogleEntry> emptyList()));
        startAnimation();

        final Intent intent = getIntent();
        paramResourceTitle = intent.getStringExtra(PARAM_RESOURCE_TITLE);
        setTitle("Move " + paramResourceTitle);
    }

    @Override
    void dbServiceConnected() {
        super.dbServiceConnected();
        downloadCollections(true);
    }

    @Override
    protected int getContentView() {
        return R.layout.collectionview;
    }

    @Override
    protected void getControls() {
        setSpinningWheel(findViewById(R.id.cv_ly_wheel));
        setRefreshImage((ImageView) findViewById(R.id.cv_wheel));
        setListView((ListView) findViewById(R.id.cv_listview));
        setTxtListEmpty((TextView) findViewById(R.id.cv_empty));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, MENU_REFRESH, 1, "Refresh");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case MENU_REFRESH:
                downloadCollections(false);
                return true;
            default:
                return false;
        }
    }

    /**
     * Starts download of all collections for display.
     * @param useCache whether the cache should be used or not
     */
    private void downloadCollections(boolean useCache) {
        setListAdapter(new GoogleEntryListAdapter(this, Collections.<GoogleEntry> emptyList()));
        startAnimation();
        clearData();
        new Thread(new DownloadCollectionsRunnable(useCache)).start();
    }

    /**
     * When an item has been selected, the selected id is put into an intent and send back to the caller.
     * @param position position of the selected item
     */
    @Override
    protected void itemSelected(final int position) {
        final GoogleEntry entry = (GoogleEntry) getListAdapter().getItem(position);
        final Intent data = new Intent();
        data.putExtra(RESULT_SELECTED_RESOURCE_ID, entry.getSimpleResourceId());
        setResult(RESULT_OK, data);
        finish();
    }

    // -------------------------------- INNER CLASSES ---------------------------------

    /**
     * Class for background thread that performs the actual download of all collections.
     */
    private class DownloadCollectionsRunnable implements Runnable {

        /** Flag to control whether the cache should be used. */
        private boolean useCache;

        /**
         * Creates a new runnable for downloading Google collections.
         * @param useCache true if the cache should be used, false otherwise.
         */
        public DownloadCollectionsRunnable(boolean useCache) {
            this.useCache = useCache;
        }

        /** {@inheritDoc} */
        public void run() {
            try {
                final GoogleAPI api = getGoogleUtil().getAPI();
                final Message msg = new Message();
                getData().add(ROOT_COLLECTION);
                getData().addAll(api.getAllCollections(getDb(), useCache));
                msg.what = MSG_DOWNLOAD_COMPLETE;
                getDownloadHandler().sendMessage(msg);
            } catch (IOException ie) {
                final Message msg = new Message();
                msg.what = MSG_DOWNLOAD_ERROR;
                msg.obj = ie;
                getDownloadHandler().sendMessage(msg);
            }
        }
    }
}
